import React, { Component } from 'react'
import { withRouterContext } from '@/context/router/routerContext'
import { getContext } from '@/context/common/applicationContext'
import { Spin } from 'antd'
import { post, get } from '@/utils/requestUtil.js'
import hljs from 'highlight.js'
import {
  FormOutlined, CommentOutlined, LikeOutlined, StarOutlined, EyeFilled, LikeFilled, StarFilled,
  ClockCircleFilled, InteractionFilled, ArrowUpOutlined
} from '@ant-design/icons'
import CustomerCard from '@/components/viewWidget/CustomerCard'
import { commonQueryByCode } from '@/service/document/documentService'
import { Link } from 'react-router-dom'
import './index.css'
import 'highlight.js/styles/github.css'
import './richText.css'
import CommentsMasked from '@/components/viewWidget/CommentsMasked'
import RichTextRenderer from '@/components/viewWidget/RichTextRenderer/RichTextRender'

class BlogView extends Component {

  constructor(props) {
    super(props)
    this.state = {
      loading: true,
      blog: null,
      customer: null,
      blogStatus: null,
      returnTopDisplay: false, //返回顶部显隐
      blogLabel: [], // 博客个人标签
      commentDisplay: false, //评论显隐
    }
  }

  async componentDidMount() {
    const { customerId, id } = this.props.routerParams //客户id和博客id

    let blog = null
    let customer = null
    let blogStatus = null
    let blogLabel = []

    //博客基本信息
    const response = await get(`/blog/get/${id}`)
    if (response && response.data) blog = response.data
    //用户信息
    const custResponse = await get(`/customer/get/${customerId}`)
    if (custResponse && custResponse.data) customer = custResponse.data
    //博客状态信息
    const statusResponse = await get(`/blog/${id}/status/${this.props.user.id}`)
    if (statusResponse && statusResponse.data) blogStatus = statusResponse.data
    //博客个人标签获取
    const blogLabelResponse = await commonQueryByCode({
      commandCode: 'getBlogClassByBlogId',
      searchFactory: [
        {
          fieldName: 'blogId',
          fieldValue: id,
          operate: 'eq'
        }
      ]
    })
    if (blogLabelResponse && blogLabelResponse.data && Array.isArray(blogLabelResponse.data.documents)) {
      blogLabel = blogLabelResponse.data.documents.map(item => item.content)
    }

    await new Promise(resolve => {
      this.setState({
        blog,
        customer,
        blogStatus,
        blogLabel
      }, resolve)
    })

    if (blog && customer && blogStatus) {
      await new Promise(resolve => { this.setState({ loading: false }, resolve) })
      hljs.highlightAll() //代码高亮
      await post(`/blog/${id}/view/${this.props.user.id}`) //增加浏览量
      window.addEventListener('scroll', this.handleScroll) //滚动条监视
    }
  }

  async componentWillUnmount() {
    window.removeEventListener('scroll', this.handleScroll)
  }

  handleScroll = () => {
    if (document.body.scrollTop > 120 || document.documentElement.scrollTop > 120) {
      if (this.state.returnTopDisplay === false) this.setState({ returnTopDisplay: true })
      else return
    } else {
      if (this.state.returnTopDisplay === true) this.setState({ returnTopDisplay: false })
      else return
    }
  }

  scrollToTop = () => {
        const c = Math.max(
            document.documentElement.scrollTop,
            document.body.scrollTop,
            0 // 防止负值
        );

        // 终止条件：当滚动距离小于等于1像素时停止
        if (c <= 5) {
            this._scrollId && window.cancelAnimationFrame(this._scrollId);
            this._scrollId = null;
            return window.scrollTo(0, 0);
        }

        // 缓动计算：使用二次缓出函数（更自然）
        const target = c - (c / 8);

        // 执行滚动
        window.scrollTo(0, target);

        // 存储动画帧ID用于后续取消
        this._scrollId = requestAnimationFrame(this.scrollToTop);
    }

  onAgreeClick = async () => {
    await post(`/blog/${this.state.blog.id}/agree/${this.props.user.id}`)
    await this.flushBlogAndBlogStatus() //页面重载
  }

  onCollectionClick = async () => {
    await post(`/blog/${this.state.blog.id}/collection/${this.props.user.id}`)
    await this.flushBlogAndBlogStatus() //页面重载
  }

  flushBlogAndBlogStatus = async () => {
    let blog = null
    let blogStatus = null
    const response = await get(`/blog/get/${this.state.blog.id}`)
    if (response && response.data) blog = response.data
    const statusResponse = await get(`/blog/${this.state.blog.id}/status/${this.props.user.id}`)
    if (statusResponse && statusResponse.data) blogStatus = statusResponse.data
    await new Promise(resolve => {
      this.setState({
        blog,
        blogStatus
      }, resolve)
    })
  }

  render() {
    if (this.state.loading === true) return <Spin />
    return (
      <div className='blog-view-main'>
        <div className='blog-view-main-left'>
          <div className='blogView-customerCard'>
            <CustomerCard
              customer={this.state.customer}
              user={this.props.user}
            ></CustomerCard>
          </div>
        </div>

        <div className='blog-view-main-right'>
          <div className='right-title'>
            <div className='title'>{this.state.blog.blogTitle}</div>
          </div>
          <div className='blogView-data-statistics'>
            <span className='data-statistics-item'>
              {
                this.state.blog.createTime === this.state.blog.alterTime ?
                  <span><ClockCircleFilled />发布于 {this.state.blog.createTime}</span> :
                  <span data-tooltip-bottom={'发布于 ' + this.state.blog.createTime}>
                    <InteractionFilled />修改于 {this.state.blog.alterTime}
                  </span>
              }
            </span>
            <span className='data-statistics-item'><EyeFilled />浏览量 {this.state.blog.views}</span>
            <span className='data-statistics-item'>
              <LikeFilled style={this.state.blogStatus.agreeStatus === 'true' ? { color: 'var(--danger-font-color)' } : null} />
              点赞数 {this.state.blog.agree}
            </span>
            <span className='data-statistics-item'>
              <StarFilled style={this.state.blogStatus.collectionStatus === 'true' ? { color: 'var(--font-fifteen)' } : null} />
              收藏 {this.state.blog.collection}
            </span>
          </div>
          <div className='right-content richText'>
            <RichTextRenderer html={this.state.blog.htmlText} />
          </div>
          <div className='right-label'>
            <span>标签：</span>
            {
              this.state.blogLabel.length > 0 ?
                this.state.blogLabel.map(item => {
                  return (
                    <span style={{ margin: '0 5px' }} key={item.id}>
                      <Link to={`/user/${this.state.customer.id}`} state={{ classId: item.id }}>{item.className}</Link>
                    </span>
                  )
                }) : '无'
            }
          </div>
        </div>

        <div className='blog-view-tool'>
          <div className='blog-view-tool-item'
            data-tooltip-left={this.state.blogStatus.agreeStatus === 'true' ? '取消点赞' : '点赞'}
            style={this.state.blogStatus.agreeStatus === 'true' ? { color: 'var(--danger-font-color)' } : null}
            onClick={this.onAgreeClick}
          ><LikeOutlined /></div>
          <div className='blog-view-tool-item'
            data-tooltip-left={this.state.blogStatus.collectionStatus === 'true' ? '取消收藏' : '收藏'}
            style={this.state.blogStatus.collectionStatus === 'true' ? { color: 'var(--font-fifteen)' } : null}
            onClick={this.onCollectionClick}
          ><StarOutlined /></div>
          <div className='blog-view-tool-item'
            onClick={async () => {
              const oldCommentDisplay = this.state.commentDisplay
              await new Promise(resolve => {
                this.setState({
                  commentDisplay: !oldCommentDisplay
                }, resolve)
              })
            }}
            data-tooltip-left='评论'
          ><CommentOutlined /></div>
          {
            this.props.user.id === this.state.customer.id ?
              <div
                className='blog-view-tool-item'
                onClick={() => { this.props.navigate(`/write/blog/${this.state.blog.id}`) }}
                data-tooltip-left='编辑'
              ><FormOutlined /></div> : ''
          }
          {
            this.state.returnTopDisplay === true ?
              <div className='blog-view-tool-item'
                data-tooltip-left='返回顶部'
                onClick={this.scrollToTop}
              >
                <ArrowUpOutlined />
              </div> : ''
          }
        </div>

        <CommentsMasked
          visual={this.state.commentDisplay}
          blogId={this.state.blog.id}
          blogAuthorId={this.state.customer.id}
          user={this.props.user}
          onCancel={async () => {
            await new Promise(resolve => {
              this.setState({
                commentDisplay: false
              }, resolve)
            })
          }}
        ></CommentsMasked>
      </div>
    )
  }
}

export default getContext(withRouterContext(BlogView))
